package com.wkbb.basic.service.impl;

import com.wkbb.basic.mapper.*;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.SysFunctionService;
import com.wkbb.basic.vo.SysFunctionVo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.handler.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Lilin
 */
@Service
@Slf4j
public class SysFunctionServiceImpl extends BaseServiceImpl<SysFunction> implements SysFunctionService {

    @Autowired
    private SysFunctionMapper mapper;

    @Autowired
    public void setMapper(SysFunctionMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public List<SysFunctionVo> getFunctionTreeList(Map<String, Object> params)
    {
        return mapper.getFunctionTreeList(params);
    }

    @Override
    @Transactional
    public void updateFunction(SysFunction sysFunction)
    {
        Long id = sysFunction.getId();

        //先修改
        mapper.update(sysFunction);

        //如果禁用，则子功能全部禁用
        if(null != sysFunction.getStatus()) {
            List<SysFunction> childList = new ArrayList<SysFunction>();

            //递归查询子功能
            this.getChildFunctionList(childList, sysFunction.getId(),sysFunction.getStatus());

            if (childList.size() > 0) {
                mapper.updateBatch(childList);
            }
        }
    }

    //递归查询子功能
    private void getChildFunctionList(List<SysFunction> childList,Long parentId,Boolean staus)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("parentId",parentId);
        List<SysFunction> childFunctionList = mapper.getListByMapParams(params);
        if(childFunctionList.size()>0)
        {
            for(SysFunction sysFunction : childFunctionList) {
                sysFunction.setStatus(staus);
                childList.add(sysFunction);
                this.getChildFunctionList(childList,sysFunction.getId(),staus);
            }
        }
    }
}
